#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re
import sys
import os
import time
import threading
import datetime
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from mpl_toolkits.mplot3d import Axes3D
'''
import urlparse
#导入请求包
import requests
'''

matplotlib.rcParams[u'font.sans-serif'] = ['simhei']
matplotlib.rcParams['axes.unicode_minus'] = False


def writefile(content, filepath, di):
    fp = open(filepath, di)
    fp.write(content)
    return fp.close()

def readfile(filepath):
    fp = open(filepath, 'r')
    fileread = fp.read()
    fp.close()
    return fileread

def runMysql():
    global starttime2
    time.sleep(20)

    starttime2 = datetime.datetime.now()
    os.system("./exe > /dev/null 2>&1")
    os.system("./exe > /dev/null 2>&1")
    os.system("./exe > /dev/null 2>&1")
    os.system("./exe > /dev/null 2>&1")


    endtime = datetime.datetime.now()
    global isMysql
    isMysql = 1
    print "Mysql:" + str((endtime - starttime2).total_seconds())

def runRedis():
    #starttime = datetime.datetime.now()
    for num in range(1,40000):
        os.system("redis-cli -h 127.0.0.1 -p 6379 get key%d > /dev/null 2>&1" % (random.randint(1,10000)))
        global redis_thread
        redis_thread = redis_thread + 1

    endtime = datetime.datetime.now()
    global isRedis
    isRedis = 1
    print "Redis:" + str((endtime - starttime).total_seconds())

def intt(s):
    s = s[::-1]
    num = 0
    for i, v in enumerate(s):
	offset = ord(v) - ord('0')
	num += offset * (10 ** i)
    return num
    
def simple_plot2():
    


    x = [1, 2, 4, 5]
    xt= [1.5, 2.5, 4.5, 5.5]
    height = [0, 0, 0, 0]
    weight = [1, 1, 1, 1]
    xlabel = ['MySQL','Redis']
    pl = 0

    last_mysql = 0
    last_redis = 0
    last_time = 0
    last_time2 = 0
    flag = 0
    flag2 = 0
    global redis_thread, mysql_thread
   
    for i in range(3000):

	mysqlstr = readfile("mysql-thread-num")

        mysql_thread = intt(readfile("mysql-thread-num"))

	cmd = "ps -ef | grep ResourceMonitor | grep -v grep"
	if flag == 0:
	    re = os.system(cmd)
	if re == 0 and flag == 0:
            flag = 1
	    pl = pl + 2 
            
	    last_mysql = mysql_thread
            last_redis = redis_thread
	    last_time = (datetime.datetime.now() - starttime).total_seconds()
	    last_time2 = (datetime.datetime.now() - starttime2).total_seconds()

	if flag2==0 and mysql_thread>0:
	    flag2 = 1
	    last_mysql = mysql_thread
            last_redis = redis_thread
	    last_time = (datetime.datetime.now() - starttime).total_seconds()
            last_time2 = (datetime.datetime.now() - starttime2).total_seconds()


	plt.cla()
	plt.bar(x, height, weight, color=['darkorange', 'royalblue', 'darkorange', 'royalblue'])
	plt.title(u"Mysql和Redis平均每操作的执行时间")
	plt.xticks(xt, xlabel )
	plt.ylabel(u"平均每操作的执行时间(ms)")
	plt.ylim(0, 100)
	plt.xlim(1, 6)

	for xi in range(4):
		plt.annotate('{}'.format(height[xi]),
                    xy=(xt[xi] , height[xi]),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
	
	plt.pause(4)
	mysqlstr = readfile("mysql-thread-num")

        mysql_thread = intt(readfile("mysql-thread-num"))
        global redis_thread

        endtime = datetime.datetime.now()
	runtime = (endtime - starttime).total_seconds() -last_time
        runtime2 = (endtime - starttime2).total_seconds() -last_time2

        global isMysql, isRedis
        if isMysql == 0 and isRedis == 0:
	    height[pl] = float('%.2f' % (runtime2/max(mysql_thread-last_mysql, 1) * 100 *10))#100 *20))
	    if mysql_thread==0:
		height[pl] = 0
	    print "time", str(float('%.2f' %(endtime - starttime).total_seconds()))
            #print("first:",height[0:4])
        if isMysql == 0 and isRedis == 0:
	    height[pl+1] = float('%.2f' % (runtime/max(redis_thread-last_redis, 1) *100 *10)) #*100 *50))
	    if redis_thread==0:
		height[pl+1] = 0
            #print("second:",height[0:4])

	'''
	#加发送四组数据代码
	print("height",height[0:4])	
	url = 'http://10.5.113.191:8086/proxy/responseTime'
        data = {
    		'mysql_old':height[0],
    		'redis_old':height[1],
    		'mysql_new':height[2],
                'redis_new':height[3],
	}
	lt = []
	for k,v in data.items():
    		lt.append(k+'='+str(v))
	query_string = '&'.join(lt)
	print(lt)
	print(query_string)
	url = url + '?'+query_string
	print(url)
	
	n = 0
	while n < 10:
		n = n + 1
		r = requests.get(url)
		if r.status_code==200:
			printf(r.status_code, "connect success")
			break

	'''

    plt.show()

if __name__ == '__main__':
    global isMysql, isRedis, starttime, starttime2, redis_thread
    isMysql = 0
    isRedis = 0
    redis_thread = 0


    tm1 = 0
    tr1 = 0


    starttime = datetime.datetime.now()
    starttime2 = datetime.datetime.now()
    threadMysql = threading.Thread(target=runMysql, args=())
    threadRedis = threading.Thread(target=runRedis, args=())
    threadPlot2  = threading.Thread(target=simple_plot2, args=())

    threadMysql.start()
    threadRedis.start()
    threadPlot2.start()

    threadMysql.join()
    threadRedis.join()
    threadPlot2.join()
    

    
